package com.ln.controller.impl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ln.common.MD5;
import com.ln.common._ObjFac;
import com.ln.controller.BaseController;
import com.ln.dto.ParamsMap;
import com.ln.pojo.impl.UserInfoPOJO;
import com.ln.pojo.impl.UserPOJO;
import com.ln.service.impl.UserInfoService;
import com.ln.service.impl.UserService;

@Controller
@RequestMapping("setting")
public class SettingController extends BaseController {
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private UserService userService;
	
	@RequestMapping
	public String index(HttpServletRequest request, Model model) {
		return info(request, model);
	}
	
	@RequestMapping(value = "info", method = RequestMethod.GET)
	public String info(HttpServletRequest request, Model model) {
		UserPOJO LOGIN_USER = getLoginUser(request);
		if (LOGIN_USER==null) {
			return "redirect:/login";
		}
		UserInfoPOJO  userInfoPOJO = userInfoService.selectOne(LOGIN_USER.getId());
		model.addAttribute("INFO", userInfoPOJO);
		return "setting/index_info";
	}
	
	@RequestMapping(value = "pass", method = RequestMethod.GET)
	public String pass(HttpServletRequest request, Model model) {
		UserPOJO LOGIN_USER = getLoginUser(request);
		if (LOGIN_USER==null) {
			return "redirect:/login";
		}
		return "setting/index_pass";
	}
	
	@ResponseBody
	@RequestMapping(value = "info", method = RequestMethod.POST)
	public Object info(HttpServletRequest request, UserInfoPOJO userInfoPOJO) {
		
		userInfoPOJO.setUser_id(getLoginUserId(request));
		userInfoService.save(userInfoPOJO);
		
		return _ObjFac.cloneResponseBodyJSON(1, "信息已保存", null);
	}
	
	@ResponseBody
	@RequestMapping(value = "pass", method = RequestMethod.POST)
	public Object pass(HttpServletRequest request, @RequestParam("thispass") String thispass,
			@RequestParam("newpass") String newpass, @RequestParam("repass") String repass) {
		
		UserPOJO LOGIN_USER = getLoginUser(request);
		if (!MD5.md5(thispass).equals(userService.selectPassword(LOGIN_USER.getId()))) {
			return _ObjFac.cloneResponseBodyJSON(-5, "当前密码错误，修改失败！", null);
		}
		
		if (!newpass.equals(repass) || newpass.length() == 0) {
			return _ObjFac.cloneResponseBodyJSON(-5, "确认密码与新密码不一致，修改失败！", null);
		}
		
		userService.updatePassword(ParamsMap.create(2).add("id", LOGIN_USER.getId()).add("password", MD5.md5(newpass)));
		
		return _ObjFac.cloneResponseBodyJSON(1, "密码已修改", null);
	}
}